package com.jsb.laundry.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.jsb.laundry.common.config.Constant;
import com.jsb.laundry.common.enums.ReturnStatusCode;
import com.jsb.laundry.common.response.WebResponse;
import com.jsb.laundry.common.utils.JSBUtil;
import com.jsb.laundry.common.utils.http.HttpUtil;
import com.jsb.laundry.model.dto.DeliveryListRequest;
import com.jsb.laundry.model.entity.FactoryList;
import com.jsb.laundry.model.vo.DeliveryListVo;
import com.jsb.laundry.model.vo.FactoryListVo;
import com.jsb.laundry.model.vo.ListVo;
import com.jsb.laundry.model.vo.WaybillListVo;
import com.jsb.laundry.service.DriverService;
import com.jsb.laundry.service.OrderSplittingServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Api(tags = {"司机"})
@RestController
@RequestMapping("driver")
public class DriverController {
    @Resource
    private DriverService driverService;
    @Resource
    private OrderSplittingServiceImpl orderSplittingService;
    @ApiOperation(value = "工厂列表待待取件", notes = "工厂列表待待取件", httpMethod = "POST")
    @PostMapping("findByFactoryList")
    public WebResponse findByFactoryList(@RequestBody JSONObject object){
        String driverStatus = object.getString("driverStatus");
        List<FactoryList> byList = driverService.findByList(driverStatus);
        for (FactoryList factoryList : byList) {

            if ("0".equals(factoryList.getShopsType())){
                factoryList.setShopsType("普通店铺");
            }
            if ("1".equals(factoryList.getShopsType())){
                factoryList.setShopsType("旗舰店");
            }
            if ("2".equals(factoryList.getShopsType())){
                factoryList.setShopsType("工厂");
            }
        }
        return WebResponse.successData(byList);
    }
    @ApiOperation(value = "司机状态", notes = "司机状态", httpMethod = "POST")
    @PostMapping("findByDriverStatus")
    public WebResponse findByDriverStatus(@RequestBody JSONObject object){
        String userId = object.getString("userId");
        String byDriverStatus = driverService.findByDriverStatus(userId);
        return WebResponse.successData(byDriverStatus);
    }
    @ApiOperation(value = "工厂列表", notes = "工厂列表", httpMethod = "POST")
    @PostMapping("factoryList")
    public WebResponse factoryList(){
        List<FactoryListVo> factoryListVo = driverService.factoryList();
        return WebResponse.successData(factoryListVo);
    }
    @ApiOperation(value = "待取件列表", notes = "待取件列表", httpMethod = "POST")
    @PostMapping("listPicked")
    public WebResponse listPicked(@RequestBody JSONObject object){
        String shopsId = object.getString("shopsId");
        String status = object.getString("status");
        String driverStatus = object.getString("driverStatus");
        FactoryList factory =  driverService.findByFactory(shopsId,driverStatus);
        if ("0".equals(factory.getShopsType())){
            factory.setShopsType("普通店铺");
        }
        if ("1".equals(factory.getShopsType())){
            factory.setShopsType("旗舰店");
        }
        if ("2".equals(factory.getShopsType())){
            factory.setShopsType("工厂");
        }
        HashMap map = new HashMap();
        List<WaybillListVo> EwaybillListVos = driverService.exceptionList(shopsId);
        List<WaybillListVo> waybillListVos = driverService.orderList(shopsId,driverStatus);
        int allNum = waybillListVos.size();
        if ("0".equals(driverStatus)){
             allNum += EwaybillListVos.size();
        }
        factory.setNum(String.valueOf(allNum));

        if ("1".equals(status)){

            map.put("waybillListVos",EwaybillListVos);
        }else if ("0".equals(status)){

            map.put("waybillListVos",waybillListVos);

        }
        map.put("num",waybillListVos.size());
        map.put("factory",factory);
        map.put("Enum",EwaybillListVos.size());
        return WebResponse.successData(map);

    }
    @ApiOperation(value = "更新检查状态", notes = "检查状态", httpMethod = "POST")
    @PostMapping("checkStatus")
    public WebResponse checkStatus(@RequestBody JSONObject object){
        String orderItemId = object.getString("orderItemId");
        String driverStatus = object.getString("driverStatus");
        int i = driverService.checkStatus(orderItemId,driverStatus);
        return WebResponse.successData(i);

    }
    @ApiOperation(value = "查询订单信息", notes = "查询订单信息", httpMethod = "POST")
    @PostMapping("queryOrderInformation")
    public WebResponse queryOrderInformation(@RequestBody JSONObject object){
        String lsOrderId = object.getString("orderItemId");//ls
        String driverStatus = object.getString("driverStatus");//ls
        String orderItemId= driverService.findByorderItemId(lsOrderId);
        WaybillListVo waybillListVo = driverService.queryOrderInformation(orderItemId,driverStatus);
        if (JSBUtil.isEmptyObject(waybillListVo)){
            return WebResponse.success(ReturnStatusCode.THE_CURRENT_ORDER_DOES_NOT_MATCH.getCode(), ReturnStatusCode.THE_CURRENT_ORDER_DOES_NOT_MATCH.getMsg());
        }
        return WebResponse.successData(waybillListVo);
    }
    @ApiOperation(value = "异常单", notes = "异常单", httpMethod = "POST")
    @PostMapping("exceptionData")
    public WebResponse exceptionData(@RequestBody JSONObject object){
        String orderItemId = object.getString("orderItemId");
        //查询异常单是否有
        int rExceptionData = driverService.rExceptionData(orderItemId);
        if (rExceptionData==1){
           return WebResponse.success(ReturnStatusCode.ABNORMAL_ORDER_ALREADY_EXISTS.getCode(), ReturnStatusCode.ABNORMAL_ORDER_ALREADY_EXISTS.getMsg());

        }
        String img = object.getString("img");
        String problem = object.getString("problem");
        String orderId = driverService.findByOrderIdItme(orderItemId);
        //查询订单的方向
        String orderDirection = driverService.findByDirectionOrderId(orderId);
        //更新订单异常状态
        int updExceptionStatus = driverService.updExceptionStatus(orderItemId);
        String findByOrderFulfillmentsId = driverService.findByOrderFulfillmentsId(orderItemId);
        //入库
        int addException = driverService.addException(findByOrderFulfillmentsId,orderDirection,orderItemId);
        //更新图片和问题描述
        int updException =driverService.updException(img,problem,orderItemId);
        if ("1".equals(orderDirection)){
            int updateOrder = driverService.updateOrder(orderItemId);
        }else{
            int updateFactory = driverService.updateFactory(orderItemId);

        }
        return WebResponse.successData(updException);
    }
    @ApiOperation(value = "异常单列表", notes = "异常单列表", httpMethod = "POST")
    @PostMapping("exceptionList")
    @Transactional
    public synchronized WebResponse exceptionList(@RequestBody JSONObject object){
        String shopsId = object.getString("shopsId");
        String driverStatus = object.getString("driverStatus");
        FactoryList factory =  driverService.findByFactory(shopsId,driverStatus);
        if ("0".equals(factory.getShopsType())){
            factory.setShopsType("普通店铺");
        }
        if ("1".equals(factory.getShopsType())){
            factory.setShopsType("旗舰店");
        }
        if ("2".equals(factory.getShopsType())){
            factory.setShopsType("工厂");
        }
        HashMap map = new HashMap();
        List<WaybillListVo> waybillListVos = driverService.exceptionList(shopsId);
        List<FactoryListVo> factoryListVo = driverService.factoryList();
        FactoryListVo listVo = factoryListVo.get(0);
        for (WaybillListVo waybillListVo : waybillListVos) {
            if ("1".equals(waybillListVo.getOrderDirection())){
                waybillListVo.setCome(waybillListVo.getShopsAddress());
            }else {
                waybillListVo.setBack(waybillListVo.getShopsAddress());
            }
        }

        map.put("factory",factory);
        map.put("waybillListVos",waybillListVos);
        return WebResponse.successData(map);
    }

    @ApiOperation(value = "批量操作", notes = "批量操作", httpMethod = "POST")
    @PostMapping("bulkOperation")
    public WebResponse bulkOperation(@RequestBody JSONObject object){
        JSONArray list = object.getJSONArray("subOrderIdList");
        String driverStatus = object.getString("driverStatus");
        if (JSBUtil.isEmptyObject(list)){
            return WebResponse.success(ReturnStatusCode.PLEASE_ENTER_THE_NECESSARY_PARAMETERS.getCode(), ReturnStatusCode.PLEASE_ENTER_THE_NECESSARY_PARAMETERS.getMsg());
        }
        List<String> orderIdList= driverService.findByOrderId(list);//批量查询

        List<String> byDirection = driverService.findByDirectionList(list);//批量查询
        for (Object o : byDirection) {//方向 取
            if ("1".equals(o)){
                if ("1".equals(driverStatus)){//取件
                    int updateShops = driverService.shopOrdersItemStatus(list);//批量更改
                    int updateOrderStatus = driverService.updateOrderStatus(orderIdList,"2");//批量更改
                    int updateDriver = driverService.driverOrdersItemStatus(list,"1","1");//司机状态
                }else if ("2".equals(driverStatus)){//送达
                    int updateOrderStatus = driverService.updateOrderStatus(orderIdList,"3");//批量更改
                    int updateDriver = driverService.driverOrdersItemStatus(list,"2","1");//司机状态
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("subOrderIds",list);

                    for (Object o1 : list) {
                        //查询订单是工厂还是店铺
                        String nextToShopsId = driverService.findByShopsId(o1.toString());//findByShopsId
                        String shopsType = driverService.findByShopsType(nextToShopsId);
                        if ("1".equals(shopsType)){
                            //订单进入小站
                            JSONObject shops = new JSONObject();
                            shops.put("subOrderIds",list);
                            String post = HttpUtil.sendPost("http://127.0.0.1:30000/admin/laundryShops/orderEnterShopsPlus", null, JSONObject.toJSONString(shops));
                            //分账
                            for (String s : orderIdList) {
                                orderSplittingService.driverAccounting("5a389899fe0c4c77abea000f8489de51", s, Constant.driver_money);
                            }
                        }else if ("2".equals(shopsType)){
                            //订单进入工厂
                            String post = HttpUtil.sendPost("http://127.0.0.1:30000/admin/laundryFactory/orderEnterFactory", null, JSONObject.toJSONString(jsonObject));
                            //分账
                            for (String s : orderIdList) {
                                orderSplittingService.driverAccounting("5a389899fe0c4c77abea000f8489de51", s, Constant.driver_money);
                            }

                        }

                        //findByOrderId
                         String findByOrderIdStr =  driverService.findByOrderIdStr(o1.toString());
                        int addOrderDriver = driverService.addOrderDriver(findByOrderIdStr,o1.toString(),o.toString());
                    }
                }

            }else {//方向 送
                if ("1".equals(driverStatus)){//取件
                    int updateFac = driverService.factoryOrdersStatus(list);//批量更改
                    int updateOrderStatus = driverService.updateOrderStatus(orderIdList,"2");//批量更改
                    int updateDriver = driverService.driverOrdersItemStatus(list,"1","2");//司机状态
                }else if ("2".equals(driverStatus)){//送达
//                  int updateOrderStatus = driverService.updateOrderStatus(orderIdList,"3");//批量更改
                    int updateDriver = driverService.driverOrdersItemStatus(list,"2","2");//司机状态
                    //订单进入小站
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("subOrderIds",list);
                    String post = HttpUtil.sendPost("http://127.0.0.1:30000/admin/laundryShops/orderEnterShopsBack", null, JSONObject.toJSONString(jsonObject));
                    for (Object o1 : list) {
                        //findByOrderId
                        String findByOrderIdStr =  driverService.findByOrderIdStr(o1.toString());
                        int addOrderDriver = driverService.addOrderDriver(findByOrderIdStr,o1.toString(),o.toString());
                        //分账
                        for (String s : orderIdList) {
                            orderSplittingService.driverAccounting("5a389899fe0c4c77abea000f8489de51", s, Constant.driver_money);
                        }
                    }
                    int updateShopsStatus =  driverService.updateShopsStatus(list);

                }

            }
        }
        return WebResponse.successData("1");
    }
    @ApiOperation(value = "查询该站点扫描的商品", notes = "查询该站点扫描的商品", httpMethod = "POST")
    @PostMapping("productsScanned")
    public WebResponse productsScanned(@RequestBody JSONObject object){
        String shopsId = object.getString("shopsId");
        String driverStatus = object.getString("driverStatus");
        if (JSBUtil.isEmptyObject(shopsId)){
            return WebResponse.success(ReturnStatusCode.PLEASE_ENTER_THE_NECESSARY_PARAMETERS.getCode(), ReturnStatusCode.PLEASE_ENTER_THE_NECESSARY_PARAMETERS.getMsg());
        }
        List<ListVo> productsScanned= driverService.productsScanned(driverStatus,shopsId);
        return WebResponse.successData(productsScanned);
    }

    @ApiOperation(value = "送达列表", notes = "送达列表", httpMethod = "POST")
    @PostMapping("deliveryList")
    public WebResponse deliveryList(@RequestBody DeliveryListRequest deliveryListRequest){
        PageHelper.startPage(deliveryListRequest.getPageNum(), deliveryListRequest.getPageSize());
       List<DeliveryListVo>  list = driverService.deliveryList(deliveryListRequest.getKeywords(),deliveryListRequest.getStartTime(),deliveryListRequest.getEndTime());
       return WebResponse.successData(list);
    }
}
